package cn.itcast.chapter05.session.example02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Author: 朱新舜
 * @Date: 2020-06-10 11:23:15
 */
@WebServlet("/indexServlet")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        resp.setContentType("text/html;charset=utf-8");
        //创建或者获取保存用户信息的Session对象
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user==null){
            resp.getWriter().print("您还没有登录，请<a href='/CaoGao/login.html'>登录</a>");
        } else {
            resp.getWriter().print("您已登录，欢迎你，"+user.getUsername()+"!");
            resp.getWriter().print("<a href='/CaoGao/logoutServlet'>退出</a>");
            //创建Cookie存放Session的标志号
            Cookie cookie = new Cookie("JSESSIONID",session.getId());
            cookie.setMaxAge(60*30);
            cookie.setPath("/CaoGao");
            resp.addCookie(cookie);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
